//
//  RegisterView.swift
//  Kosspot
//
//  Created by 李鑫 on 2025/7/3.
//

import SwiftUI
import ToastUI

struct RegisterView: View {
    @EnvironmentObject var appState:AppState
    @StateObject var viewModel = LoginViewModel()
    @State private var scene = "register"
    @State private var isAgreed = false
    @State private var showToast = false

    var body: some View {
        VStack {
            ZStack {
                Image("6528")
                    .resizable()
                    .frame(height: 194)
                
                Image("Kosspot")
                    .resizable()
                    .frame(width: 116,height: 52)
                VStack {
                    Image("6711")
                        .resizable()
                        .frame(width: 143,height: 26)
                        .padding(.top,35)
                        .padding(.leading,-22)
                }
            }
            
            ZStack(alignment: .leading) {
                RoundedRectangle(cornerRadius: 8)
                    .fill(Color(hex: "#F5F6FA"))
                    .frame(height: 44)
                HStack {
                    Menu {
                        ForEach(viewModel.countryCodes, id: \.self) { item in
                            Button {
                                let components = item.components(separatedBy: "：")
                                if let countryCode = components.last?.trimmingCharacters(in: .whitespaces) {
                                    viewModel.selectedCode = countryCode
                                }
                            } label: {
                                Text(item)
                            }
                        }
                    } label: {
                        HStack(alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/, content: {
                            Text(viewModel.selectedCode)
                                .foregroundColor(.black)
                            Spacer().frame(width: 2)
                            Image("sanjiao")
                        })
                        .lineSpacing(0)
                    }
                    .frame(height: 44)
                    .padding(.leading, 18)
                    Spacer().frame(width: 8)
                    Capsule()
                        .frame(width: 1.3, height: 18)
                        .foregroundColor(Color (hex: "#B5B5B5"))

                    Spacer().frame(width: 8)
                    ZStack(alignment: .leading) {
                        if viewModel.username.isEmpty {
                            Text("请输入手机号码")
                                .font(.system(size: 16))
                                .foregroundColor(Color (hex: "#B5B5B5"))
                        }
                        TextField("", text: $viewModel.username)
                            .font(.system(size: 16))
                            .keyboardType(.phonePad)
                            .frame(height: 44)
                            .padding(.trailing, 18)
                            .foregroundColor(Color.black)
                            .autocapitalization(UITextAutocapitalizationType/*@START_MENU_TOKEN@*/.none/*@END_MENU_TOKEN@*/)
                    }
                }
            }
            .padding(.horizontal, 24)
            
            Spacer().frame(height: 16)
            
            HStack (alignment: .center, content:{
                ZStack(alignment:.leading) {
                    RoundedRectangle(cornerRadius: 8)
                        .fill(Color(hex: "#F5F6FA"))
                        .frame(height: 44)
                    if viewModel.code.isEmpty {
                        Text("请输入验证码")
                            .font(.system(size: 16))
                            .foregroundColor(Color (hex: "#B5B5B5"))
                            .padding(.leading, 18)
                    }
                    SecureField("", text: $viewModel.code)
                        .font(.system(size: 16))
                        .frame(height: 44)
                        .padding(.horizontal, 18)
                        .foregroundColor(Color.black)
                        .autocapitalization(UITextAutocapitalizationType.none)
                    
                }
                CountdownButton(mobile: $viewModel.username) {
                    viewModel.sendSMCcode(mobile: viewModel.username, scene: scene)
                }
            })
            .frame(height: 44)
            .background(Color(hex: "#F5F6FA"))
            .cornerRadius(8.0)
            .padding(.horizontal, 24)
            
            
            Spacer().frame(height: 16)
            // 密码
            ZStack(alignment:.leading) {
                RoundedRectangle(cornerRadius: 8)
                    .fill(Color(hex: "#F5F6FA"))
                    .frame(height: 44)
                if viewModel.password.isEmpty {
                    Text("请设置6-20位登录密码")
                        .font(.system(size: 16))
                        .foregroundColor(Color (hex: "#B5B5B5"))
                        .padding(.leading, 18)
                }
                SecureField("", text: $viewModel.password)
                    .font(.system(size: 16))
                    
                    .frame(height: 44)
                    .padding(.horizontal, 18)
                    .foregroundColor(Color.black)
                    .autocapitalization(UITextAutocapitalizationType.none)
                
            }
            .padding(.horizontal, 24)
            
            
            Spacer().frame(height: 16)
            // 密码
            ZStack(alignment:.leading) {
                RoundedRectangle(cornerRadius: 8)
                    .fill(Color(hex: "#F5F6FA"))
                    .frame(height: 44)
                if viewModel.passwordAgain.isEmpty {
                    Text("请再次输入新的登录密码")
                        .font(.system(size: 16))
                        .foregroundColor(Color (hex: "#B5B5B5"))
                        .padding(.leading, 18)
                }
                SecureField("", text: $viewModel.password)
                    .font(.system(size: 16))
                    
                    .frame(height: 44)
                    .padding(.horizontal, 18)
                    .foregroundColor(Color.black)
                    .autocapitalization(UITextAutocapitalizationType.none)
                
            }
            .padding(.horizontal, 24)
            HStack {
                Spacer()
                Button(action: {
                    if viewModel.username.isEmpty {
                        viewModel.error = "请输入手机号码"
                        return
                    }
                    if viewModel.code.isEmpty {
                        viewModel.error = "请输入验证码"
                        return
                    }
                    if viewModel.password.isEmpty {
                        viewModel.error = "请设置密码"
                        return
                    }
                    
                    if viewModel.passwordAgain.isEmpty {
                        viewModel.error = "请再次输入密码"
                        return
                    }
                    
                    if !isAgreed {
                        viewModel.error = "请同意用户服务协议"
                        return
                    }
                    viewModel.error = nil


                }, label: {
                    HStack(alignment: .center, spacing: 0) {
                        Text("立即注册")
                            .font(.system(size: 16))
                            .foregroundColor(Color(hex: "#242424"))
                    }
                    .frame(maxWidth: .infinity, alignment: .center)
                })
                .padding()
                .alert(isPresented: $viewModel.isLoginSuccess, content: {
                    Alert(title: Text("提示"), message: Text("注册成功!"), dismissButton: .default(Text("确认"), action: {
                        viewModel.isLoginSuccess = false
                        viewModel.error = nil
                        appState.navigateBack()
                    })
                    )
                })
                Spacer()
            }
            .gradientBackground(colors: [Color(hex: "#00F3AF"),Color(hex: "#00E9DA")])
            .cornerRadius(8.0)
            .padding([.trailing,.leading],24)
            .padding(.top, 16)
            
            Button("已有账户，立即登录") {
                appState.navigateBack()
            }.font(.system(size: 14))
                .foregroundColor(Color(hex: "#D5D5D5"))
                .padding(.top,16)
            
            Spacer()
            HStack {
                Toggle("", isOn: $isAgreed)
                    .toggleStyle(CustomToggleStyle())
                Text("已阅读并同意")
                    .font(.system(size: 14))
                    .foregroundColor(Color(hex: "#888888"))
                Spacer().frame(width: 0)
                Button(action: {
                    //《用户服务协议》
                }) {
                     Text("《用户服务协议》").foregroundColor(Color(hex: "#00E9DA"))
                        .font(.system(size: 14))
                        .foregroundColor(Color(hex: "#00E9DA"))
                        .padding(.vertical, 10)
                }
            }
            .frame(height: 14)
            .padding(.top,30)
            .padding(.bottom,47)
        }
        .navigationBarHidden(true)
        .background(Color(hex: "#0A0A0A"))
        .edgesIgnoringSafeArea(.all)
        .dismissingKeyboard()
        .toast(isPresented: $showToast) {
            ShowMessageView(message: viewModel.error)
        }
        .onChange(of: viewModel.error) {
            newValue in
            if let errorMessage = newValue, !errorMessage.isEmpty {
                showToast = true
                DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                    showToast = false
                    viewModel.error = nil
                }
            }
        }
    }
}

#Preview {
    RegisterView()
}
